package com.ssyc.student.activity;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ssyc.common.adapter.VpCommonAdapter;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.glide.ImageUtil;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UIHelper;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.vp.SuperViewPager;
import com.ssyc.student.R;
import com.ssyc.student.bean.WriteInfo;
import com.ssyc.student.fragment.StudentWriteAnswerFragment;
import com.ssyc.student.fragment.StudentWriteIntentFragment;
import com.ssyc.student.util.RecordTimeUtil;
import com.ssyc.student.util.TimeCount;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;


/**
 * 学生端--写作界面
 */

public class StudentWriteActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {

    //返回图标
    private ImageView ivBack;

    //写作题目的内容
    private TextView tvContent;

    //写作的tips
    private TextView tvTips;

    //写作的素材
    private ImageView ivImg;

    //显示ViewPager页面的文本
//    private TextView tvVpPos;

    //ViewPager
    private SuperViewPager vp;


    //是否是第一次进入页面
    private boolean isFirst = true;

    //填充ViewPager的Fragment集合
    private List<Fragment> mFragments;

    //ViewPager的适配器
    private VpCommonAdapter adapter;

    //记录当前ViewPager滑动的位置
    private int pos = 0;

    //Handler对象
    private Handler handler = new Handler();

    //用于保存做题的选择题目答案的Map,key为当前的位置,value为选择的答案
    public static Map<Integer, String> chooseAnswerMap;

    //用于保存用户答题的对错的Map,key为当前的位置,value为答题的状态值
    public static Map<Integer, Boolean> answerMap;

    //获取LessonId的key
    public static final String LESSONID = "lessonid";

    //获取GradeId的key
    public static final String GRADEID = "gradeid";

    //LessonId
    private String lessonId;

    //GradeId
    private String gradeId;

    private Intent intent;

    //json
    private String dataJson;

    //记录用户保存的时间
    public static long firstTime;

    //时间rowid
    private String rowId;

    //静态代码块
    {
        //这里使用有序的Map来存放题目
        chooseAnswerMap = new LinkedHashMap<>();
        answerMap = new LinkedHashMap<>();


        //记录用户第一次进入的时间
        firstTime = System.currentTimeMillis();

        //初始化计时器
        TimeCount.init();
    }

    //获取保存答题Map的方法
    public static Map<Integer, String> getChooseAnswerMap() {
        return chooseAnswerMap;
    }

    //获取保存答题正确或者错误Map的方法
    public static Map<Integer, Boolean> getAnswerMap() {
        return answerMap;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_write;
    }

    @Override
    protected void init() {
        showContent();
        //初始化控件
        initView();
        //获取传递过来的对象
        initIntent();
        //请求服务器
        http();
    }

    /**
     * 获取传递过来的对象
     */
    private void initIntent() {
        lessonId = getIntent().getStringExtra(LESSONID);
        gradeId = getIntent().getStringExtra(GRADEID);

    }

    /**
     * 初始化View的控件
     */
    private void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
//        tvVpPos = findViewById(R.id.tv_vp_pos);
        tvContent = findViewById(R.id.tv_problem_content);
        tvTips = findViewById(R.id.tv_problem_tips);
        ivImg = findViewById(R.id.iv_problem_img);
        vp = findViewById(R.id.vp);
        vp.addOnPageChangeListener(this);

    }

    /**
     * 初始化Fragments的方法,需要在请求服务器后获取到数据后执行
     */
    private void initFragments(WriteInfo info) {

        mFragments = new ArrayList<>();

        for (int i = 0; i < info.getData().get(0).getQuestion_list().get(0).getDetail_list().size(); i++) {
            mFragments.add(StudentWriteAnswerFragment.newInstance(GsonUtil.objectToJson(info.getData().get(0).getQuestion_list().get(0)), i));
        }

        //添加最后一个跳转页面的Fragment
        mFragments.add(StudentWriteIntentFragment.newInstance(GsonUtil.objectToJson(info.getData().get(0).getQuestion_list().get(0)),
                info.getData().get(0).getQuestion_list().get(0).getDetail_list().size()+1));

        //设置当前展示的Vp的页码
//        tvVpPos.setText("1/" + (mFragments.size()-1));

        for (int i = 0; i < info.getData().get(0).getQuestion_list().get(0)
                .getDetail_list().size(); i++) {
            getChooseAnswerMap().put(i, "");
        }
    }



    /**
     * 亮屏进入
     */
    @Override
    protected void onResume() {
        super.onResume();

        //记录进入时间
        RecordTimeUtil.httpEnterTime(this,lessonId,gradeId, "16",
                new RecordTimeUtil.onRecordRowIdListener() {
                    @Override
                    public void recordRowId(String id,String en) {

                        rowId = id;
                    }
                });
    }

    /**
     * 息屏结束计时
     */
    @Override
    protected void onPause() {
        super.onPause();

        //提交结束时间

    }



    /**
     * 请求服务器
     */
    private void http() {

        Map<String, String> map = new HashMap<>();
        map.put("type", "23");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("lesson", "Lesson" + lessonId);
        map.put("examtype", "16");
        map.put("platform", "8");
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("role", AccountUtils.getRole(this));

        HttpUtils.post(HttpAdress.WRITE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast("网络错误", false);
            }

            @Override
            public void onResponse(String response, int id) {
                showContent();
                WriteInfo info = null;
                try {
                    info = GsonUtil.jsonToBean(response, WriteInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("test", "数据解析异常");
                }
                Log.i("test", response);
                if (null != info) {
                    if ("200".equals(info.getState())) {
                        //返回成功初始化

                        //写作内容
                        tvContent.setText(info.getData().get(0).getQuestion_list().get(0).getQuestion());

                        //tips
                        tvTips.setText(info.getData().get(0).getQuestion_list().get(0).getQuestion_answer());

                        //图片素材
                        ImageUtil.displayImage(getBaseContext(), ivImg, info.getData().get(0).getQuestion_list().get(0).getWriting_material().get(0).getMaterial());

                        //初始化Fragments
                        initFragments(info);
                        //初始化Vp的操作
                        initVp();

                        dataJson = GsonUtil.objectToJson(info.getData().get(0).getQuestion_list().get(0));
                    } else {
                        Log.i("test", info.getState());
                    }
                }
            }
        });
    }

    /**
     * 设置ViewPager的方法
     */
    private void initVp() {
        adapter = new VpCommonAdapter(getSupportFragmentManager(), mFragments);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(mFragments.size());
    }

    /**
     * ViewPager的滚动监听事件
     *
     * @param position
     * @param positionOffset
     * @param positionOffsetPixels
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        pos = position;
//        if (position != mFragments.size() - 1) {
//            tvVpPos.setVisibility(View.VISIBLE);
//            tvVpPos.setText((position + 1) + "/" + (mFragments.size() - 1));
//        } else {
//            tvVpPos.setVisibility(View.GONE);
//        }

        if(position==mFragments.size() -1){
            boolean isNull = false;
            for (int i=0;i<chooseAnswerMap.size();i++){
                if(TextUtils.isEmpty(chooseAnswerMap.get(i))){
                    isNull =true;
                }
            }
            if(isNull){
                UIHelper.showToast(this,"请完成全部写作题目");
            }else{
                intent = new Intent(this, StudentWriteTwoActivity.class);
                intent.putExtra("json",dataJson);
                intent.putExtra(LESSONID,lessonId);
                intent.putExtra(GRADEID,gradeId);
                intent.putExtra("rowid",rowId);
                startActivity(intent);
            }

            if(mFragments.size()>1){
                vp.setCurrentItem(mFragments.size()-2);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 接受事件的方法
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        //通知ViewPager翻页
        if (null != busInfo && StudentWriteAnswerFragment.WRITEVPSCOLL.equals(busInfo.vpScoll)) {
            pos += 1;

//            vp.setCurrentItem(pos);

            //延迟800毫秒跳转页面
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    vp.setCurrentItem(pos);
                }
            }, 300);
        }
    }

    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        }
    }
}
